include(ExternalProject)

CPMAddPackage(
    NAME ffmpeg
    GIT_REPOSITORY https://gitee.com/ls56647426/ffmpeg.git
    GIT_TAG n4.4
    DOWNLOAD_ONLY YES
)

macro(add_ffmpeg_library target)
    add_library(${target} SHARED IMPORTED)
    if(NOT TARGET ${target})
        message("not target ${target}.")
    endif()
    set_target_properties(${target} PROPERTIES
        IMPORTED_LOCATION_RELEASE ${ffmpeg_SOURCE_DIR}/build/lib/lib${target}.so
        IMPORTED_LOCATION_DEBUG ${ffmpeg_SOURCE_DIR}/build/lib/lib${target}.so
    )
    execute_process(COMMAND rm -rf
        ${LIBRARY_OUTPUT_PATH}/lib${target}.so
    )
    execute_process(COMMAND ln -s
        ${ffmpeg_SOURCE_DIR}/build/lib/lib${target}.so
        ${LIBRARY_OUTPUT_PATH}/lib${target}.so
    )
endmacro()

# ffmpeg has no CMakeLists, so we create our own target
if(ffmpeg_ADDED)
    ExternalProject_Add(ffmpeg
        SOURCE_DIR ${ffmpeg_SOURCE_DIR}
        LOG_DIR ${ffmpeg_SOURCE_DIR}/log
        BINARY_DIR ${ffmpeg_SOURCE_DIR}/build
        CONFIGURE_COMMAND cd ${ffmpeg_SOURCE_DIR} && ./configure
            --enable-shared
            --prefix=${ffmpeg_SOURCE_DIR}/build
            --disable-x86asm
        BUILD_COMMAND cd ${ffmpeg_SOURCE_DIR} && make -j4
        INSTALL_COMMAND cd ${ffmpeg_SOURCE_DIR} && make install
    )

    set(FFMPEG_LIBRARYS avcodec avdevice avfilter avformat avutil swresample swscale)

    foreach(library ${FFMPEG_LIBRARYS})
        add_ffmpeg_library(${library})
    endforeach()
endif()
